#pragma once

#include <winsock2.h>
#include <map>
#include <list>
#include <string>
using namespace std;

#include "TinyThread.h"
//#include "TinyThreadPool.h"
#include "TinyMsgBuffer.h"

#define TINYSOCKETTCPSIZE 1024*4
#define TCPHBTIMEOUT 210
#define RECEIVEMSG_WAIT_TIMEOUT 3

namespace TinyCC{
	namespace TCP{

		class CTinyTCPClient:public Loki::ObjectLevelLockable<CTinyTCPClient>
		{
		public:
			CTinyTCPClient(void);
			virtual ~CTinyTCPClient(void);
		protected:
			BOOL _convertIPAddr(const char* ip,BYTE* output);
			SOCKET m_clientsock;
			TinyCC::msg::CTinyRawMsgBuffer m_SendMsgBuff;
			TinyCC::msg::CTinyRawMsgBuffer m_ReceiveMsgBuff;
			HANDLE m_hRecEvent;
			//CTCPAtomMsg<CTCPHBHead> m_HBMsg;
			CTinyThread* m_RecvThread;
			CTinyThread* m_SendThread;
			HANDLE m_connectedEvent;
			HANDLE m_hExitEvent;
			bool m_connected;
			CTinyThread *m_pRecvThread;
		public:
			void init();
			bool sendData(void* data,long datalen);
			bool connectToServer(const char* rip,int rport, HANDLE& recEvent );
			bool disconnect( );
			inline HANDLE getRecHandle() const{	return m_hRecEvent;	}
			TinyCC::msg::CTinyTCPRawMsg* getNextMsg( );
			void clearData();
			void _recvThread(void* pParam);
			SOCKET getSocketId(){return m_clientsock;}
			HANDLE getConnectedEvent(){return m_connectedEvent;}
			void setIsConnected(bool state){m_connected = state;}
			void resetConnectedEvent(){ResetEvent(m_connectedEvent);}
			bool getIsConnected(){return m_connected;}

		public:
			void processTimer();
		};
	}
}
